package cn.xd.security.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.xd.base.application.service.command.GlobalAppUserAppService;
import cn.xd.common.enums.auth.AppUserTypeEnum;
import cn.xd.common.enums.auth.ThirdPartyTypeEnum;
import cn.xd.common.response.ResponseResult;
import cn.xd.security.command.UserPhoneByCodeQuery;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 公开的
 */
@Slf4j
@RestController
@RequestMapping("/public/api/security")
public class PublicSecurityController {
    @Resource(name = "MainMiniAppService")
    private WxMaService selfMiniAppService;

    @Resource
    private GlobalAppUserAppService globalAppUserAppService;

    /**
     * 通过code获得手机号（null代表未曾登录）
     *
     * @param code
     * @return
     */
    @PostMapping("getPhone/mainCustomer")
    public ResponseResult<String> getPhoneBySelfMiniApp(@Validated @RequestBody UserPhoneByCodeQuery code) {
        try {
            Integer type = ThirdPartyTypeEnum.WECHAT_MINI_APP.getCode();
            Integer appUserType = AppUserTypeEnum.MAIN_CUSTOMER.getCode();
            WxMaJscode2SessionResult sessionInfo = selfMiniAppService.getUserService().getSessionInfo(code.getCode());
            return ResponseResult.success(globalAppUserAppService.getGlobalAppUserPhone(sessionInfo.getOpenid(), sessionInfo.getUnionid(), type, appUserType));
        } catch (WxErrorException e) {
            log.error("WxErrorException" + e);
            return ResponseResult.success(null);

        }
    }
}
